//
//  AppDelegate.m
//  奇闻
//
//  Created by 似水灵修 on 14-11-20.
//  Copyright (c) 2014年 MingYueGuCheng. All rights reserved.
//

#import "AppDelegate.h"
#import "MYOAuthViewController.h"
#import "MYAccountTool.h"
#import "MYChooseContrllerTool.h"
#import <AVFoundation/AVFoundation.h>
#import "SDImageCache.h"
#import "SDWebImageManager.h"
#import "MYHttpTool.h"
#import "MBProgressHUD+MJ.h"

@interface AppDelegate ()<UIAlertViewDelegate>
@property (nonatomic, strong) AVAudioPlayer *player;//播放器
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    if (launchOptions) {
        // 获取本地通知对象
        UILocalNotification *localNotif = launchOptions[UIApplicationLaunchOptionsLocalNotificationKey];
        // 有本地通知,才要显示
        if (localNotif) {
            [self showLocalNotif:localNotif];
        }
    }
    // 注册提醒通知
    if (iOS8) {// ios8才需要注册通知
        UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
        [application registerUserNotificationSettings:setting];
    }
    //1.创建窗口
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    //4.显示窗口
    [self.window makeKeyAndVisible];
    //2.创建根控制器,包装UITabBarController
    //获取accessToken
    //是否有用户信息
    MYAccount *account = [MYAccountTool account];
    if (account.access_token) {//有accessToken,有用户信息
        //判断是否有新特性
        //当前版本号
        // 选择进入新特性还是首页
        // 判断有没有新特性,从而选择窗口的根控制器
        [MYChooseContrllerTool chooseRootViewController:MYKeyWindow];
    }
    else {//无用户信息
        //请求用户授权
        MYOAuthViewController *oauthVC = [[MYOAuthViewController alloc] init];
        //3.设置根控制器
        self.window.rootViewController = oauthVC;
    }
    //监控当前网络
    [MYHttpTool monitorHttpStateChangedResult:^(NSString *result) {
        //判断当前网络状态
        regularString(&result) ? [MBProgressHUD showSuccess:result] : [MBProgressHUD showError:result];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [MBProgressHUD hideHUD];
//        });
    }];
    return YES;
}
#pragma -mark 正则表达式
bool regularString(NSString *__autoreleasing *str)
{
    bool falg = NO;//default 没有网络
    NSString *pattern = @"\\d";
//    NSRegularExpressionCaseInsensitive 不区分大小写
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:NULL];
    NSArray *resultArrayI = [regular matchesInString:*str options:NSMatchingReportCompletion range:NSMakeRange(0, (*str).length)];
    if (resultArrayI.count) {
        for (NSTextCheckingResult *result in resultArrayI) {
                falg = [*str substringWithRange:result.range].intValue;
        }
    }
    *str = [*str substringFromIndex:1];
    return falg;
}

//接收本地推送消息(程序被关掉后,不会调用此方法)
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
    [self showLocalNotif:notification];
}
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    if (!iOS8) {
        // 开启后台任务,这个时间是不确定,由系统决定.如果后台任务被关掉,程序就不能后台运行
        __weak typeof(application) weakApplication = application;
         __block UIBackgroundTaskIdentifier taskID = [weakApplication beginBackgroundTaskWithExpirationHandler:^{
            // 程序关闭的时候,就会调用
            // 主动关闭后台任务
            [weakApplication endBackgroundTask:taskID];
        }];
    }
    // 播放一个没有声音的Mp3,目的是需要告诉苹果,我在播放东西,并不需要让用户听到.
    // 创建本地播放对象
    // url:要播放文件的url
    // 获取url,从bundle里面获取
    // 获取本地播放文件的url
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"silent.mp3" withExtension:nil];
    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
    //无限循环
    player.numberOfLoops = -1;
    self.player = player;
    [player prepareToPlay];
    [player play];
    
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    [self.player stop];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application
{
    //赶紧清除所有的内存缓存
    [[SDImageCache sharedImageCache] clearMemory];
    //赶紧停止正在进行的图片下载操作
    [[SDWebImageManager sharedManager] cancelAll];
}
- (void)showLocalNotif:(UILocalNotification *)notification
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提醒" message:notification.alertBody delegate:self cancelButtonTitle:@"知道了" otherButtonTitles:@"稍后再提醒", nil];
    [alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (0 == buttonIndex) {//知道了
        [[UIApplication sharedApplication] cancelAllLocalNotifications];
    }
}
@end
